﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace ace_pso
{
    public partial class TraceMessageCtrl : UserControl
    {
        public TraceMessageCtrl()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Gets/Sets the test displayed in the trace window
        /// </summary>
        public string TraceText
        {
            get { return traceInfoRText.Text; }
            set { traceInfoRText.Text = value; }
        }

        private bool _AutoConnect = false;

        /// <summary>
        /// Determines whether the control will connect to trace events when it becomes visible, and disconnect when it is hidden
        /// </summary>
        [Category("Behavior")]
        [Browsable(true)]
        [DefaultValue(false)]
        [Description("Determines whether the control will connect to trace events when it becomes visible, and disconnect when it is hidden")]
        public bool AutoConnect
        {
            get { return _AutoConnect; }
            set { _AutoConnect = value; }
        }

        /// <summary>
        /// Clears the contents of the window
        /// </summary>
        public void Clear()
        {
            this.traceInfoRText.Clear();
        }

        /// <summary>
        /// Raises the VisibleChanged event
        /// </summary>
        /// <param name="e">event arguments</param>
        protected override void OnVisibleChanged(EventArgs e)
        {
            if (AutoConnect)
            {
                if (this.Visible)
                    Connect();
                else
                    Disconnect();
            }
            base.OnVisibleChanged(e);
        }

        private TextWriterTraceListener listener = null;

        /// <summary>
        /// Connects the control to trace events
        /// </summary>
        public void Connect()
        {
            listener = new TextWriterTraceListener(new RichTextBoxWriter(this.traceInfoRText));

            Trace.Listeners.Add(listener);
        }

        /// <summary>
        /// Disconnects the control from trace events
        /// </summary>
        public void Disconnect()
        {
            if (listener != null)
            {
                Trace.Listeners.Remove(listener);
                listener.Flush();
                listener.Close();
                listener = null;
            }
        }
    }
}
